<?php


namespace app\admin\model;


use app\common\constants\AdminConstant;
use app\common\model\TimeModel;
use think\Model;

class SystemAdmin extends TimeModel
{

    protected $deleteTime = 'delete_time';

    public function branch()
    {
        return $this->belongsTo('app\admin\model\SystemBranch', 'from_branch', 'branch_id');
    }


    public function getAuthList()
    {
        $list = (new SystemAuth())
            ->where('status', 1)
            ->column('title', 'id');
        return $list;
    }


    /**
     * 根据信息自动检测pid,完成pids
     * @param array $data
     */
    public function checkPid(array $data)
    {
        $data['pid'] = $data['pid'] ?? 1;
        $parent_admin_info = $this->find($data['pid']);
        if (!$parent_admin_info) {
            return error('请写入正确的上级管理员id');
        }
        $new_pids = $parent_admin_info->pids ? $parent_admin_info->pids . $parent_admin_info->id . ',' : ',' . $parent_admin_info->id . ',';
        if (isset($data['id'])) {//编辑需要检测死循环
            if ($data['id'] == AdminConstant::SUPER_ADMIN_ID) {
                return error('超级管理员不允许修改');
            }
            $admin_info = $this->find($data['id']);
            //检测是否有死循环
            $pids = str2arr($new_pids);
            if (in_array($admin_info->id, $pids)) {
                return error('上级管理员队列中不能包含自己');
            }
        } else {//新增需要加密密码
            if (isset($data['password']) && isset($data['password_confirm'])) {
                unset($data['password_confirm']);
                $data['password'] = password($data['password']);
            } else {
                unset($data['password'], $data['password_confirm']);
            }
        }
        $data['pids'] = $new_pids;
        return success($data);
    }

    /**
     * @title 快捷获取admin列表
     * @param mixed $field
     * @param mixed $where
     * @author FashionJune
     */
    public function getAdminList($field = '*', $where = true)
    {
        return $this->where($where)->field($field)->select();
    }

}